<?php

class IpnbaseController extends Zend_Controller_Action {
   
   protected $_fields = array(
      'cartPayment' => array(
        'paymentstatus',
        'buyer_email',
        'firstname',
        'lastname',
        'street',
        'city',
        'state',
        'zipcode',
        'country',
        'mc_gross',
        'mc_fee',
        'memo',
        'paymenttype',
        'paymentdate',
        'txnid',
        'pendingreason',
        'reasoncode',
        'tax',
        'datecreation'
      ),
      'subscriptionPayment' => array(
        'paymentstatus',
        'buyer_email',
        'firstname',
        'lastname',
        'street',
        'city',
        'state',
        'zipcode',
        'country',
        'mc_gross',
        'mc_fee',
        'memo',
        'paymenttype',
        'paymentdate',
        'txnid',
        'pendingreason',
        'reasoncode',
        'tax',
        'datecreation'
      ),
      'cart' => array(
        'txnid',
        'itemnumber',
        'itemname',
        'os0',
        'on0',
        'os1',
        'on1',
        'quantity',
        'invoice',
        'custom'
      ),
      'payment' => array(
         'paymentstatus',
         'buyer_email',
         'firstname',
         'lastname',
         'street',
         'city',
         'state',
         'zipcode',
         'country',
         'mc_gross',
         'mc_fee',
         'itemnumber',
         'itemname',
         'os0',
         'on0',
         'os1',
         'on1',
         'quantity',
         'memo',
         'paymenttype',
         'paymentdate',
         'txnid',
         'pendingreason',
         'reasoncode',
         'tax',
         'datecreation'
      ),
      'subscription' => array(
         'subscr_id ',
         'sub_event',
         'subscr_date',
         'subscr_effective',
         'period1',
         'period2',
         'period3',
         'amount1',
         'amount2',
         'amount3',
         'mc_amount1',
         'mc_amount2',
         'mc_amount3',
         'recurring',
         'reattempt',
         'retry_at',
         'recur_times',
         'username',
         'password',
         'payment_txn_id',
         'subscriber_emailaddress',
         'datecreation'
      )
   );
   
   private function bind($source, $keys, $dest) {
      if(!$dest) {
         $dest = array();
      }
      foreach($keys as $key) {
         @$dest[$key] = $source[$key];
      }
      return $dest;
   }
   
   public function _createUrl() {
      // read the post from PayPal system and add 'cmd'
      $req = 'cmd=_notify-validate';
      foreach ($_POST as $key => $value) {
         $value = urlencode(stripslashes($value));
         $req .= "&$key=$value";
      }
      return $req;
   }
   
   private function _isVerified() {
      $req = $this->_createUrl();
      // post back to PayPal system to validate
      $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
      $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
      $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
      
      $fp = fsockopen ("{$this->shcema}://{$this->server}", $this->port, $errno, $errstr, 30);

      if (!$fp) {
         // HTTP ERROR
      } else {
         fputs ($fp, $header . $req);
         while (!feof($fp)) {
            $res = fgets ($fp, 1024);
            if (strcmp ($res, "VERIFIED") == 0) {
               $retval = true;
            } else if(strcmp($res, "INVALID") == 0) {
               $retval = false;
            }
         }
      }
      fclose ($fp);
      return $retval;
   }
   
   public function init() {
      $this->_helper->layout->setLayout('page');
      $this->server = isset($_POST['test_ipn']) ? 'www.sandbox.paypal.com' : 'www.paypal.com';
      $this->port = isset($_POST['test_ipn']) ? 80 : 433;
      $this->schema = isset($_POST['test_ipn']) ? 'http' : 'ssl';
      $this->view->debug = $this->server . $this->port . $this->schema;
   }
   
   public function indexAction() {
      $this->view->debug .= "<br /> in index action";
      if(!empty($_POST) && $this->_isVerified()) {
         
         $paymentInfo = new Model_PaypalPaymentInfo();
         $duplicate = $paymentInfo->findBy('txnid', $_POST['txn_id']);
         
         if($duplicate) {
            // VERIFIED DUPLICATED TRANSACTION
            return;
         }
         
         if ($_POST['txn_type'] == "cart") {
            $cartPayment = new Model_PaypalCartPayment();
            $cartPayment->insert($this->bind($_POST, $this->_fields['cartPayment']));
                        
            for ($i = 1; $i <= $_POST['num_cart_items']; $i++) {
               $data = array();
               $data['itemname'] = "item_name".$i;
               $data['itemnumber'] = "item_number".$i;
               $data['on0'] = "option_name1_".$i;
               $data['os0'] = "option_selection1_".$i;
               $data['on1'] = "option_name2_".$i;
               $data['os1'] = "option_selection2_".$i;
               $data['quantity'] = "quantity".$i;
               $cartInfo = new Model_PaypalCartInfo();
               $cartInfo->insert($data);
            }
            
            $this->cart();

         } else {
            $payment = new Model_PaypalPaymentInfo();
            $payment->insert($this->bind($_POST, $this->_fields['payment']));
            $this->payment();
         }
         
         if ($_POST['txn_type'] == "subscr_signup"  ||  $_POST['txn_type'] == "subscr_payment"  ) {
            $subscriptionPayment = new Model_PaypalSubscriptionPayment();
            $subscriptionPayment->insert($this->bind($_POST, $this->_fields['subscriptionPayment']));
            $subscription = new Model_PaypalSubcriptionInfo();
            $subscription->insert($this->bind($_POST, $this->_fields['subscription']));
            if($_POST['txn_type'] == 'subscr_signup') {
               $this->subscription_signup();
            } else if($_POST['txn_type'] == 'subscr_payment') {
               $this->subscription_payment();
            }
         } else if($_POST['txn_type'] == 'subscr-eot') {
            $this->subscription_endterm();
         }
         
      }
      

   }
   
   
   /**
    * Callback function to post process cart items
    * You could for instance update access table based on paid items
    *
    */
   protected function cart() {
      
   }
   
   /**
    * Callback function to post process payment
    *
    */
   protected function payment() {
      
   }
   
   /**
    * Callback function to post process subscription signup
    *
    */
   protected function subscription_signup() {
      
   }
   
   /**
    * Callback function to post process subscription payment
    *
    */
   protected function subscription_payment() {
      
   }
   
   /**
    * Callback function to post process subscription end of term
    *
    */
   protected function subscription_endterm() {
      
   }
}

